import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    islogin: sessionStorage.getItem("islogin"),
    phone: sessionStorage.getItem("phone"),
    //1.在vuex中设置一个能装数据的空数组作为公共区域
    // shopCart:[]
    shopCart: []
  },
  mutations: {
    logined(state, phone) {
      state.islogin = true,
        state.phone = phone
    },
    //2.设置添加数据进购物车的方法
    // addCar(state,val){
    //   state.shopCart.push(val)
    // },
    addCar(state, val) {
      if (state.shopCart.length != 0) {
        let count = 0
        state.shopCart.map(item => {
          if (item.lid == val.lid) {
            item.count++
            count++
          }
        })
        if (count === 0) {
          state.shopCart.push(val)
          console.log(1)
        }
      } else {
        state.shopCart.push(val);
      }

    },
    // 5.设置vuex方法把购物车组件删除后剩余的数据存入vuex中shopCart中
    // setShop(state,val){
    //   state.shopCart = val
    // }
    setShop(state, val) {
      state.shopCart = val
    }
  },
  actions: {
    // 封装函数异步执行，并修改phone的值
    vlogin(context, obj) {
      return new Promise(
        function (resolve, reject) {
          axios.post("/users/login", obj).then(result => {
            console.log(result.data);
            if (result.data.code === 200) {
              context.commit(
                "logined", result.data.results[0].phone
              );
              resolve();
            } else {
              reject(result.data.msg);
            }
          })
        }
      )
    }
  },
  modules: {}
})